package com.bndg.browser

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.AutoCompleteTextView
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.KeyboardUtils
import com.bndg.browser.db.AppDatabase
import com.bndg.browser.db.InputHistory
import com.bndg.browser.ui.CommonActivity
import com.bndg.browser.ui.HistoryActivity
import com.bndg.browser.ui.InputHistoryAdapter
import com.hjq.base.BaseActivity
import com.hjq.base.BaseDialog
import com.hjq.demo.ui.dialog.BottomMenuDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber

class MainActivity : BaseActivity() {

    private var isShowSoftInput: Boolean = false
    private val urlInput: AutoCompleteTextView? by lazy { findViewById(R.id.url_input) }
    private val mainLayout: View? by lazy { findViewById<View>(R.id.main_layout) }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        // 绑定输入框
        // 设置手势检测器
        val gestureDetector = GestureDetector(this, GestureListener())

        // 设置触摸事件监听
        mainLayout?.setOnTouchListener { _, event ->
            gestureDetector.onTouchEvent(event)
            true
        }
        // 设置 AutoCompleteTextView
        urlInput?.setAdapter(InputHistoryAdapter(this@MainActivity, emptyList())) // 更新适配器
        urlInput?.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                val query = s.toString()

                if (query.isNotEmpty()) {
                    // 在后台线程中查询历史记录
                    lifecycleScope.launch(Dispatchers.IO) {
                        // 执行耗时操作：数据库查询
                        val history = AppDatabase.getInstance(this@MainActivity).inputHistoryDao().searchHistory("%$query%")
                        val historyList = history.map { it.inputText }.toMutableList()

                        // 回到主线程更新UI
                        withContext(Dispatchers.Main) {
                            // 更新适配器的数据
                            val adapter = urlInput?.adapter as InputHistoryAdapter
                            adapter.clear()
                            adapter.addAll(historyList)
                            adapter.notifyDataSetChanged()
                        }
                    }
                } else {
                    // 当输入框为空时，显示全部历史记录
                    lifecycleScope.launch(Dispatchers.IO) {
                        val allHistory = AppDatabase.getInstance(this@MainActivity).inputHistoryDao().getAll()
                        val allHistoryList = allHistory.map { it.inputText }.toMutableList()

                        withContext(Dispatchers.Main) {
                            val adapter = urlInput?.adapter as InputHistoryAdapter
                            adapter.clear()
                            adapter.addAll(allHistoryList)
                            adapter.notifyDataSetChanged()
                        }
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })
        // 监听edittext action search
        urlInput?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
                // 处理搜索逻辑
                KeyboardUtils.hideSoftInput(urlInput!!)
                isShowSoftInput = false
                if (urlInput?.text.toString().isNotEmpty()) {
                    lifecycleScope.launch(Dispatchers.IO) {
                        AppDatabase.getInstance(this@MainActivity).inputHistoryDao()
                            .insertOrUpdate(InputHistory(inputText = urlInput?.text.toString()))
                        withContext(Dispatchers.Main) {
                            val mainBrowserIntent = Intent()
                                .setClass(this@MainActivity, CommonActivity::class.java)
                                .putExtra("input", urlInput?.text.toString())
                            startActivity(mainBrowserIntent)
                        }
                    }
                }
                true
            } else {
                false
            }
        }
        findViewById<View>(R.id.bottom_button)?.setOnClickListener {
            BottomMenuDialog.Builder(this)
                .setListener(object : BottomMenuDialog.OnListener {
                    override fun onSelected(
                        dialog: BaseDialog?,
                        position: Int,
                        bean: BottomMenuDialog.MenuInfo
                    ) {
                        if (bean.isHistory()) {
                            startActivity(Intent(this@MainActivity, HistoryActivity::class.java))
                        }
                    }
                })
                .show()
        }
    }

    override fun initData() {
    }

    // 手势监听器
    inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
        override fun onScroll(
            e1: MotionEvent?,
            e2: MotionEvent,
            distanceX: Float,
            distanceY: Float
        ): Boolean {
            if (distanceY < 0) {
                if (!isShowSoftInput) {
                    showKeyboard()
                }
                return true
            }
            return false
        }

        override fun onSingleTapUp(e: MotionEvent): Boolean {
            Timber.d("onSingleTapUp onSingleTapUponSingleTapUp")
            Log.d(">>>>", "onSingleTapUp: ")
            KeyboardUtils.hideSoftInput(urlInput!!)
            isShowSoftInput = false
            return super.onSingleTapUp(e)
        }
    }

    override fun onClick(view: View) {
    }

    // 显示软键盘
    private fun showKeyboard() {
        isShowSoftInput = true
        urlInput?.requestFocus() // 让输入框获得焦点
        KeyboardUtils.showSoftInput(urlInput!!)
    }
}